package com.appBase;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;


import com.appBase.tools.LoadingDialog;
import com.appBase.tools.NettyServer;
import com.tencent.smtt.export.external.extension.proxy.ProxyWebChromeClientExtension;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    //    private Button button1,button2;
    public WebView webView;

    private JSInterface jsInterface;

    private long lastClickTime = 0;

    private boolean infoShow = false;




    @Override
    public void onBackPressed() {
        if (jsInterface.webViewCanBack) {
            webView.loadUrl("javascript:androidBackKeyUp()"); // hello tom
            lastClickTime = 0;
            return;
        }
        if (lastClickTime <= 0) {
            Toast.makeText(this, "再按一次后退键退出应用", Toast.LENGTH_SHORT).show();
            lastClickTime = System.currentTimeMillis();
        } else {
            long currentClickTime = System.currentTimeMillis();
            if (currentClickTime - lastClickTime < 2000) {
                NettyServer.stop();
                if (currentClickTime - lastClickTime < 2000) {
                    NettyServer.stop();
                    finish();
                } else {
                    Toast.makeText(this, "再按一次后退键退出应用", Toast.LENGTH_SHORT).show();
                    lastClickTime = System.currentTimeMillis();
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String path = this.getFilesDir().getPath() + "/web/";
        NettyServer.start(path);
        this.hideBottomUIMenu();

        getAssets().getLocales();
        webView = findViewById(R.id.localWeb);
        //关闭密码保存
        webView.getSettings().setSavePassword(false);
        webView.setWebChromeClientExtension(new ProxyWebChromeClientExtension() {
            /**
             * callback：处理后的回调；
             * schemePlusHost：域名；
             * username：用户名；
             * password：密码；
             * nameElement：用户名输入框名称；
             * passwordElement：密码输入框名称；
             * isReplace：是否是替换操作
             */
            @Override
            public boolean onSavePassword(
                    android.webkit.ValueCallback<String> callback,
                    String schemePlusHost,
                    String username,
                    String password,
                    String nameElement,
                    String passwordElement,
                    boolean isReplace) {
                //这里可以弹窗提示用户
                //这里调用将会保存用户名和密码，如果只保存用户名可以将密码置为null，如果两者均不存在则不需要调用该接口
                // password = null;
                // webView.getX5WebViewExtension().sendRememberMsg(schemePlusHost, username, password, nameElement, passwordElement);
                //处理完后需要回调该接口，执行了保存操作参数为true，否则为false
                callback.onReceiveValue("false");
                //这里要返回true，否则内核会提示用户保存密码
                return true;
            }
        });
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new CustWebViewClient());
        webView.getSettings().setDomStorageEnabled(true);// 打开本地缓存提供JS调用,至关重要
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);// 实现8倍缓存
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        String appCachePath = getApplication().getCacheDir().getAbsolutePath();
        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setDatabaseEnabled(true);
        // webView.getSettings().setSupportZoom(true);
        //设置缓存模式  禁用缓存
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        jsInterface = new JSInterface(this);
        webView.addJavascriptInterface(jsInterface, "JSInterface");
        try {
            if (jsInterface.getAppBaseUrl() == null || jsInterface.getAppBaseUrl().length() <= 0) {
                //jsInterface.setAppBaseUrl("http://10.2.6.64:8084");
                //showBaseUrlInput(false);
            } else {
                jsInterface.updateWebApp();
            }
        } catch (Exception ignored) {
        }
//        webView.loadUrl("http://192.168.31.27:8083/m.html");
        webView.loadUrl("http://127.0.0.1:53881/index.html");
        LoadingDialog.getInstance(this).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NettyServer.stop();
    }

    @Override
    public AssetManager getAssets() {
        return getResources().getAssets();
    }

    // 设置webview的一些回调 引入时是要解决webview 页面跳转的问题（window.location.href 会跳转到系统的浏览器中打开）
    private class CustWebViewClient extends WebViewClient {

        @Override
        public void onReceivedError(WebView var1, WebResourceRequest var2, WebResourceError var3) {
            super.onReceivedError(var1, var2, var3);
            LoadingDialog.getInstance(MainActivity.this).hide();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            LoadingDialog.getInstance(MainActivity.this).hide();

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }
}
